<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElDialog, ElForm, ElFormItem, ElInput, ElDatePicker, ElSelect, ElOption, ElButton, ElPagination, ElRow, ElCol } from 'element-plus'
import { queryPageApi, addApi, queryInfoApi, updateApi, deleteApi } from '@/api/clazz.js'
// 导入员工管理API
import { queryPageApi as queryEmpPageApi } from '@/api/emp.js'

// 搜索条件
const searchForm = reactive({
  name: '',
  begin: '',
  end: '',
  date: [] // 用于日期范围选择器
})

// 监听器 - 同步日期范围数据
watch(() => searchForm.date, (newVal) => {
  if(newVal && newVal.length === 2) {
    searchForm.begin = newVal[0]
    searchForm.end = newVal[1]
  } else {
    searchForm.begin = ''
    searchForm.end = ''
  }
}, { immediate: true })

// 班级列表数据
const classList = ref([])

// 分页数据 - 与员工管理保持一致
const currentPage = ref(1) //页码
const pageSize = ref(10) //每页展示记录数
const background = ref(true) //背景色
const total = ref(0) //总记录数

// 加载状态
const loading = ref(false)

// 新增/编辑对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增班级') // 对话框标题
const currentAction = ref('add') // 当前操作类型：add 或 edit
const formData = reactive({
  id: '', // 编辑时需要id
  name: '',
  room: '',
  beginDate: '',
  endDate: '',
  masterId: '',
  subject: ''
})
const formRules = reactive({
  name: [
    { required: true, message: '请输入班级名称', trigger: 'blur' }
  ],
  beginDate: [
    {
      required: true,
      message: '请选择开课时间',
      trigger: 'change'
    }
  ],
  endDate: [
    {
      required: true,
      message: '请选择结课时间',
      trigger: 'change'
    }
  ],
  subject: [
    { required: true, message: '请选择学科', trigger: 'change' }
  ]
})
const formRef = ref(null)

// 模拟数据
// 班主任列表数据（从员工模块查询job=1的员工）
const teachers = ref([])

// 学科列表数据
const subjects = ref([
  { id: 1, name: 'Java' },
  { id: 2, name: 'Python' },
  { id: 3, name: '前端' },
  { id: 4, name: '大数据' },
  { id: 5, name: 'UI设计' },
  { id: 6, name: '测试' }
])

// 查询班主任列表（job=1的员工）
const queryTeachers = async () => {
  try {
    // 查询job=1的员工，页码设为1，每页数量设为100以获取所有班主任
    const res = await queryEmpPageApi('', '', '', '', 1, 100)
    
    if (res.code === 1 && res.data) {
      // 过滤出job=1的员工作为班主任
      teachers.value = res.data.rows
        ? res.data.rows.filter(emp => emp.job === 1)
        : []
    } else {
      teachers.value = []
    }
  } catch (error) {
    console.error('查询班主任列表失败:', error)
    // 如果查询失败，使用模拟数据
    teachers.value = []
  }
}

// 查询方法
const handleSearch = async () => {
  loading.value = true
  try {
    const res = await queryPageApi(
      searchForm.name, 
      searchForm.begin, 
      searchForm.end, 
      currentPage.value, 
      pageSize.value
    )
    // 根据接口文档，返回数据结构为 {code, msg, data: {total, rows}}
    if (res.code === 1 && res.data) {
      classList.value = res.data.rows || []
      total.value = res.data.total || 0
    } else {
      classList.value = []
      total.value = 0
      ElMessage.warning(res.msg || '查询数据为空')
    }
  } catch (error) {
    ElMessage.error('查询班级列表失败')
    console.error('查询班级列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 清空方法
const handleReset = () => {
  searchForm.name = ''
  searchForm.begin = ''
  searchForm.end = ''
  searchForm.date = [] // 清空日期范围
  currentPage.value = 1
  handleSearch()
}

// 打开新增对话框
const handleAdd = () => {
  // 设置操作类型为新增
  currentAction.value = 'add'
  dialogTitle.value = '新增班级'
  
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }
  // 清空表单数据
  Object.keys(formData).forEach(key => {
    formData[key] = ''
  })
  // 显示对话框
  dialogVisible.value = true
}

// 编辑班级
const handleEdit = async (id) => {
  try {
    // 设置操作类型为编辑
    currentAction.value = 'edit'
    dialogTitle.value = '修改班级'
    
    // 确保班主任列表已加载
    if (teachers.value.length === 0) {
      await queryTeachers()
    }
    
    // 查询班级详情
    const res = await queryInfoApi(id)
    const classInfo = res.data || {}
    
    if (res.code === 1 && classInfo) {
      // 填充表单数据
      formData.id = classInfo.id || ''
      formData.name = classInfo.name || ''
      formData.room = classInfo.room || ''
      formData.beginDate = classInfo.beginDate || ''
      formData.endDate = classInfo.endDate || ''
      
      // 确保masterId与teachers数组中的id类型完全匹配
      // 先将classInfo.masterId转换为字符串
      const masterIdStr = classInfo.masterId ? String(classInfo.masterId) : ''
      
      // 查找对应的班主任对象，确保类型完全匹配
      const matchingTeacher = teachers.value.find(teacher => String(teacher.id) === masterIdStr)
      if (matchingTeacher) {
        formData.masterId = matchingTeacher.id
      } else {
        formData.masterId = ''
      }
      
      formData.subject = classInfo.subject || ''
      
      // 显示对话框
      dialogVisible.value = true
    } else {
      ElMessage.warning(res.msg || '获取班级信息失败')
    }
  } catch (error) {
    ElMessage.error('获取班级信息失败')
    console.error('获取班级信息失败:', error)
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 根据操作类型提交数据
    let res
    if (currentAction.value === 'add') {
      // 新增操作
      res = await addApi({
        ...formData,
        status: '未开班' // 默认状态为未开班
      })
    } else {
      // 编辑操作
      res = await updateApi({
        ...formData
      })
    }
    
    if (res.code === 1) {
      ElMessage.success(currentAction.value === 'add' ? '新增班级成功' : '修改班级成功')
      dialogVisible.value = false
      handleSearch() // 刷新列表
    } else {
      ElMessage.error(res.msg || (currentAction.value === 'add' ? '新增班级失败' : '修改班级失败'))
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 删除班级
const handleDelete = async (id) => {
  if (confirm('确定要删除这个班级吗？')) {
    try {
      await deleteApi(id)
      ElMessage.success('删除班级成功')
      handleSearch() // 刷新列表
    } catch (error) {
      ElMessage.error('删除班级失败')
      console.error('删除班级失败:', error)
    }
  }
}

// 分页切换 - 与员工管理保持一致
const handleSizeChange = (val) => {
  handleSearch()
}

// 页码变化时触发 - 与员工管理保持一致
const handleCurrentChange = (val) => {
  handleSearch()
}

// 页面加载时执行
onMounted(() => {
  handleSearch()
  queryTeachers() // 加载班主任列表
})
</script>

<template>
  <div class="class-management">
    <h1>班级管理</h1>
    
    <!-- 搜索区域 -->
    <div class="container">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="班级名称">
          <el-input v-model="searchForm.name" placeholder="请输入班级名称" />
        </el-form-item>
        
        <el-form-item label="结课时间">
          <el-date-picker
            v-model="searchForm.date"
            type="daterange"
            range-separator="到"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button type="info" @click="handleReset">清空</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 新增按钮 -->
    <div class="container">
      <el-button type="primary" @click="handleAdd">+ 新增班级</el-button>
    </div>
    
    <!-- 班级列表表格 -->
    <div class="container">
      <el-table 
        v-loading="loading" 
        :data="classList" 
        style="width: 100%"
        border
      >
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column label="班级名称">
          <template #default="scope">
            {{ scope.row.name.replace(/\(已编辑\)/g, '') }}
          </template>
        </el-table-column>
        <el-table-column prop="room" label="班级教室"></el-table-column>
        <el-table-column prop="masterName" label="班主任"></el-table-column>
        <el-table-column prop="beginDate" label="开课时间"></el-table-column>
        <el-table-column prop="endDate" label="结课时间"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag 
              :type="
                scope.row.status === '未开班' ? 'primary' :
                scope.row.status === '已开班' ? 'success' : 'default'
              "
            >
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="最后修改时间"></el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)" style="margin-left: 10px;">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 分页条 - 与员工管理保持一致 -->
    <div class="container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 30, 50, 75, 100]"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 新增/编辑班级对话框 -->
    <el-dialog 
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form 
        ref="formRef"
        :model="formData" 
        :rules="formRules" 
        label-width="100px"
      >
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班级名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入班级名称"></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="班级教室">
              <el-input v-model="formData.room" placeholder="请输入班级教室"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开课时间" prop="beginDate">
              <el-date-picker
                v-model="formData.beginDate"
                type="date"
                placeholder="请选择开课时间"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="结课时间" prop="endDate">
              <el-date-picker
                v-model="formData.endDate"
                type="date"
                placeholder="请选择结课时间"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 第三行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班主任">
              <el-select v-model="formData.masterId" placeholder="请选择班主任" style="width: 100%">
                <el-option 
                  v-for="teacher in teachers" 
                  :key="teacher.id" 
                  :label="teacher.name" 
                  :value="teacher.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="学科" prop="subject">
              <el-select v-model="formData.subject" placeholder="请选择学科" style="width: 100%">
                <el-option 
                  v-for="subj in subjects" 
                  :key="subj.id" 
                  :label="subj.name" 
                  :value="subj.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.class-management {
  padding: 20px;
}

.class-management h1 {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
}

.container {
  margin: 10px 0px;
}
</style>